<script setup lang="jsx">
import { ref, onMounted, reactive, nextTick, unref } from 'vue'
import { DraggableModal } from '@/components/core/draggable-modal'
import { queryPolicyInfo } from '@/api/comprehensive'
import { getByDictType } from '@/api/common'
import { useRoute } from 'vue-router'
import {
  queryCustomersList,
  getTerritory,
  getProvince,
  getProvider,
  getProviderQuery
} from '@/api/home'
import { Tooltip } from 'ant-design-vue'
import { formatColumn } from '@/utils/tools.js'
import cloneDeep from 'lodash/cloneDeep'

const hospitalInfoColumns = [
  { title: '序号', width: 80, dataIndex: 'index', key: 'index' },
  {
    title: '医院',
    width: 300,
    dataIndex: 'name',
    key: 'name',
    customRender: ({ text, record, index }) => {
      return (
        <Tooltip title={text}>
          <div
            class={{
              'pre-hospital-ellipsis-text': true
            }}
          >
            {formatColumn(text)}
          </div>
        </Tooltip>
      )
    }
  },
  {
    title: '城市',
    dataIndex: 'providerCity',
    key: 'providerCity',
    width: 120,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '签约状态 ',
    dataIndex: 'signStatus',
    key: 'signStatus',
    width: 100,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '直付许可',
    dataIndex: 'dbeligibility',
    key: 'dbeligibility',
    width: 120,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '自付比例',
    dataIndex: 'copay',
    key: 'copay',
    width: 200,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '直付类型',
    dataIndex: 'dbType',
    key: 'dbType',
    width: 160,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '医院属性',
    dataIndex: 'providerType',
    key: 'providerType',
    width: 100,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '医疗类型',
    dataIndex: 'medicalType',
    key: 'medicalType',
    width: 120,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '区',
    dataIndex: 'providerDistrict',
    key: 'providerDistrict',
    width: 100,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '国家',
    dataIndex: 'providerCountry',
    key: 'providerCountry',
    width: 120,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '省',
    dataIndex: 'providerProvince',
    key: 'providerProvince',
    width: 160,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '州',
    dataIndex: 'providerContinent',
    key: 'providerContinent',
    width: 100,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '网络内',
    dataIndex: 'isInNetwork',
    key: 'isInNetwork',
    width: 100,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: 'DBList外网显示',
    dataIndex: 'isVisibleToMember',
    key: 'isVisibleToMember',
    width: 160,
    customRender: ({ text, record, index }) => formatColumn(text)
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    fixed: 'right',
    width: 120
  }
]
const route = useRoute()
const props = defineProps({
  policyInfo: {
    type: Object,
    required: () => {}
  }
})
const emit = defineEmits(['updateVisible', 'getHospitalInfo'])

const policyInfos = ref(props.policyInfo)
const insuredList = ref([])
const formData = ref({
  memberId: policyInfos.value.member_id, //会员号
  policyYear: policyInfos.value.policyYear, //保单年度
  planTypeCode: policyInfos.value.planTypeEName, //计划类型
  insuredEffectiveDate: policyInfos.value.insuredEffectiveDate, //被保人有效期开始
  insuredExpireDate: policyInfos.value.insuredExpireDate, // 被保人有效期结束
  customerId: policyInfos.value.customer_id, //用户姓名
  dbTypeCode: [], //直付类型
  intercontinental: ['1'], //州
  nation: '8', //国家
  region: [], //省市区
  isInNetworkCode: [], //网络内
  isVisibleToMemberCode: [], //DBList外网显示
  medicalTypeCode: [], //医疗类型
  providerId: null, //医院
  providerTypeCode: [], //医院属性
  signStatusCode: [] //签约状态
})
const searchFromData = ref({})
const policyList = ref([])

async function fetchPolicyInfo() {
  const { doc_id } = unref(policyInfos.value)
  let res = null
  const data = {
    desensitization: '02',
    doc_id
  }
  try {
    res = await queryPolicyInfo(data)
  } catch (err) {
    console.log('err', err)
  }
  if (res?.isSuccess) {
    policyList.value = res?.data || []
  }
}

function handlePageChange(page, pageSize) {
  pagination.current = page
  pagination.pageSize = pageSize
  search()
}
async function getInsuredList() {
  let res = null
  try {
    const data = {
      desensitization: '02',
      insuredId: route.query.insuredId
    }
    res = await queryCustomersList(data)
  } catch (err) {
    console.log('err', err)
  }
  if (res?.isSuccess) {
    insuredList.value = res.data
  }
}

const pagination = reactive({
  current: 1,
  pageSize: 10,
  size: 'large',
  showSizeChanger: true,
  total: 0,
  onChange: handlePageChange
})
const dataSource = ref([])
const loading = ref(false)
async function initData() {
  pagination.current = 1
}
const hospitalVisible = ref(false)
onMounted(async () => {
  await nextTick()
  hospitalVisible.value = true
  getIdCardList()
  getInsuredList()
  chengeTerritory(['1'], 'init')
  changeCountry('8')
  initData()
  fetchPolicyInfo()
})
const options = ref({})
async function getIdCardList() {
  let providerproRes = await getByDictType({ dictType: 'providerpro' })
  let directpaytypeRes = await getByDictType({ dictType: 'directpaytype' })
  let medicaltypeRes = await getByDictType({ dictType: 'medicaltype' })
  let signflagRes = await getByDictType({ dictType: 'signflag' })
  let yesornoRes = await getByDictType({ dictType: 'yesorno' })
  let territoryRes = await getTerritory({ districtLVL: '1' })

  if (providerproRes.isSuccess) {
    options.value.providerpro = getByDictTypeList(providerproRes)
  }
  if (directpaytypeRes.isSuccess) {
    options.value.directpaytype = getByDictTypeList(directpaytypeRes)
  }
  if (medicaltypeRes.isSuccess) {
    options.value.medicaltype = getByDictTypeList(medicaltypeRes)
  }
  if (signflagRes.isSuccess) {
    options.value.signflag = getByDictTypeList(signflagRes)
  }
  if (yesornoRes.isSuccess) {
    options.value.yesorno = getByDictTypeList(yesornoRes)
  }
  if (territoryRes.isSuccess) {
    const list = []
    territoryRes.data &&
      territoryRes.data.length &&
      territoryRes.data.map((v) => {
        list.push({
          label: v.name,
          value: v.key
        })
      })
    options.value.territory = list
  }
}

function getByDictTypeList(res) {
  const list = []
  res.data &&
    res.data.length &&
    res.data.map((v) => {
      list.push({
        label: v.dictName,
        value: v.dictCode
      })
    })
  return list
}

function handleCancel() {
  hospitalVisible.value = false
  emit('updateVisible', false)
}
function searchForm() {
  pagination.current = 1
  searchFromData.value = cloneDeep(formData.value)
  search()
}
async function search() {
  loading.value = true
  let params = {
    ...searchFromData.value,
    policyYear: policyInfos.value.policyYear, //保单年度
    planTypeCode: policyInfos.value.planTypeEName, //计划类型
    insuredEffectiveDate: policyInfos.value.insuredEffectiveDate, //被保人有效期开始
    insuredExpireDate: policyInfos.value.insuredExpireDate, // 被保人有效期结束
    insuredId: policyInfos.value.insuredId, //insuredID
    region: selectedOptions.value, //省市区
    inputPageConfig: {
      current: pagination.current,
      size: pagination.pageSize
    }
  }
  let res = null
  try {
    res = await getProvider(removeEmptyValues(params))
  } catch (err) {
    console.log('err', err)
  } finally {
    loading.value = false
  }
  if (!res.isSuccess) return
  pagination.total = Number(res.data.total)
  dataSource.value = res.data.records.map((item) => {
    return { ...item, attachmentLoading: false }
  })
}
function reset() {
  formData.value = {
    insuredID: policyInfos.value.insuredId, //insuredID
    policyYear: policyInfos.value.policyYear, //保单年度
    planTypeCode: policyInfos.value.planTypeEName, //计划类型
    insuredEffectiveDate: policyInfos.value.insuredEffectiveDate, //被保人有效期开始
    insuredExpireDate: policyInfos.value.insuredExpireDate, // 被保人有效期结束
    customerId: policyInfos.value.customer_id, //用户姓名
    dbTypeCode: [], //直付类型
    intercontinental: [], //州
    nation: null, //国家
    region: [], //省市区
    isInNetworkCode: [], //网络内
    isVisibleToMemberCode: [], //DBList外网显示
    medicalTypeCode: [], //医疗类型
    providerIds: [], //医院
    providerTypeCode: [], //医院属性
    signStatusCode: [] //签约状态
  }
  options.value.country = []
  options.value.province = []
  providerList.value = [] // 医院支持模糊查询，也重置掉。
}
function removeEmptyValues(obj) {
  return Object.keys(obj).reduce((acc, key) => {
    if (
      obj[key] !== null &&
      obj[key] !== undefined &&
      !(typeof obj[key] === 'object' && Object.keys(obj[key]).length === 0)
    ) {
      acc[key] = obj[key]
    }
    return acc
  }, {})
}

const selectedOptions = ref([])

const filter = (inputValue, path) => {
  return path.some((option) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
}
const filterOption = (input, option) => {
  return (
    option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
    option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
  )
}
function filterByLabel(input, option) {
  if (!option.name) return
  return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
// 获取国家列表
const chengeTerritory = async (e, type) => {
  console.log('type', type)
  if (type !== 'init') {
    options.value.country = []
    options.value.province = []
    formData.value.nation = null
    formData.value.region = null
  }
  if (e.length) {
    let res = await getTerritory({ districtLVL: '2', parentKeys: e })
    if (res.isSuccess) {
      const list = []
      res.data &&
        res.data.length &&
        res.data.map((v) => {
          list.push({
            label: v.name,
            value: v.key
          })
        })
      options.value.country = list
    }
  }
}
// 国家
const changeCountry = async (country) => {
  formData.value.region = []
  options.value.province = []
  if (country) {
    let res = await getProvince({ countryKey: country })
    if (res.isSuccess) {
      options.value.province = res.data
    }
  }
}
// 省市区
const changeProvince = (e) => {
  selectedOptions.value = e.map((item) => {
    if (item.length === 1) {
      return {
        province: item[0]
      }
    }
    if (item.length === 2) {
      return {
        city: item[1],
        province: item[0]
      }
    }
    if (item.length === 3) {
      return {
        city: item[1],
        county: item[2],
        province: item[0]
      }
    }
  })
}
const providerList = ref([])
const handleChange = async (value) => {
  if (value) {
    let res = await getProviderQuery({ name: value })
    if (!res.isSuccess) return
    providerList.value = [{ name: value, code: `***${value}` }, ...res.data]
  } else {
    providerList.value = []
  }
}
// 预授权按钮
function handlePreAuth(record) {
  console.log('record', record);
  let houspitalInfo = { name: record.nameCn, providerId: record.providerId }
  emit('updateVisible', false)
  emit('getHospitalInfo', houspitalInfo)
}
</script>
<template>
  <DraggableModal
    :showCloseIcon="true"
    :footer="null"
    @cancel="handleCancel"
    v-model:open="hospitalVisible"
    :showSearchPageLink="false"
    width="1300px"
    title="医院信息"
  >
    <div class="main-header">
      <a-row :gutter="[16, 20]">
        <a-col class="gutter-row" :span="5">
          <p class="title">会员ID</p>
          <a-input v-model:value="formData.memberId" :disabled="true" />
        </a-col>
        <a-col class="gutter-row" :span="5">
          <p class="title">客户姓名</p>
          <a-select
            v-model:value="formData.customerId"
            :disabled="true"
            optionFilterProp="customerId"
            style="width: 100%"
            :field-names="{ label: 'name', value: 'customerId' }"
            :options="insuredList"
          >
          </a-select>
        </a-col>
        <a-col class="gutter-row" :span="5">
          <p class="title">保单年度</p>
          <a-input
            :disabled="true"
            :value="policyInfos.policyYear"
            placeholder="保单年度"
            allow-clear
          />
        </a-col>
        <a-col class="gutter-row" :span="5">
          <p class="title">计划类型</p>
          <a-input
            :disabled="true"
            :value="policyInfos.planTypeEName"
            placeholder="计划类型"
            allow-clear
          />
        </a-col>
        <a-col class="gutter-row" :span="5">
          <p class="title">被保人有效期</p>
          <a-input
            class="mr-20"
            :value="`${policyInfos.insuredEffectiveDate} ~ ${policyInfos.insuredExpireDate}`"
            placeholder="有效期"
            :disabled="true"
          />
        </a-col>
        <a-col class="gutter-row" :span="5">
          <p class="title">州</p>
          <a-select
            v-model:value="formData.intercontinental"
            style="width: 100%"
            placeholder="请选择"
            allowClear
            :filter-option="filterOption"
            :options="options.territory"
            @change="(val) => chengeTerritory(val, 'search')"
            mode="multiple"
          >
          </a-select>
        </a-col>
        <a-col class="gutter-row" :span="5">
          <p class="title">国家</p>
          <a-select
            v-model:value="formData.nation"
            style="width: 100%"
            placeholder="请选择"
            allowClear
            show-search
            :filter-option="filterOption"
            :options="options.country"
            @change="changeCountry"
          >
          </a-select>
        </a-col>
        <a-col class="gutter-row" :span="5">
          <p class="title">省市区</p>
          <a-cascader
            v-model:value="formData.region"
            style="width: 100%; overflow: hidden"
            multiple
            allowClear
            :maxTagCount="1"
            :options="options.province"
            :show-search="{ filter }"
            placeholder="请选择"
            @change="changeProvince"
          >
          </a-cascader>
        </a-col>
        <a-col class="gutter-row" :span="5">
          <p class="title">医院</p>
          <a-select
            v-model:value="formData.providerIds"
            show-search
            allowClear
            mode="multiple"
            :maxTagCount="1"
            :show-arrow="false"
            style="width: 100%"
            placeholder="请选择"
            optionFilterProp="children"
            :filterOption="filterByLabel"
            :field-names="{ label: 'name', value: 'code' }"
            :options="providerList"
            @search="handleChange"
          >
          </a-select>
        </a-col>

        <a-col class="gutter-row" :span="5">
          <p class="title">医院属性</p>
          <a-select
            v-model:value="formData.providerTypeCode"
            style="width: 100%"
            allowClear
            mode="multiple"
            max-tag-count="responsive"
            placeholder="请选择"
            :options="options.providerpro"
          >
          </a-select>
        </a-col>
        <a-col class="gutter-row" :span="5">
          <p class="title">直付类型</p>
          <a-select
            v-model:value="formData.dbTypeCode"
            mode="multiple"
            allowClear
            max-tag-count="responsive"
            style="width: 100%"
            placeholder="请选择"
            :options="options.directpaytype"
          >
          </a-select>
        </a-col>
        <a-col class="gutter-row" :span="5">
          <p class="title">医疗类型</p>
          <a-select
            v-model:value="formData.medicalTypeCode"
            mode="multiple"
            allowClear
            max-tag-count="responsive"
            style="width: 100%"
            placeholder="请选择"
            :options="options.medicaltype"
          >
          </a-select>
        </a-col>
        <a-col class="gutter-row" :span="5">
          <p class="title">签约状态</p>
          <a-select
            v-model:value="formData.signStatusCode"
            mode="multiple"
            max-tag-count="responsive"
            style="width: 100%"
            allowClear
            placeholder="请选择"
            :options="options.signflag"
          >
          </a-select>
        </a-col>
        <a-col class="gutter-row" :span="5">
          <p class="title">网络内</p>
          <a-select
            v-model:value="formData.isInNetworkCode"
            mode="multiple"
            allowClear
            max-tag-count="responsive"
            style="width: 100%"
            placeholder="请选择"
            :options="options.yesorno"
          >
          </a-select>
        </a-col>
        <a-col class="gutter-row" :span="5">
          <p class="title">DBList外网显示</p>
          <a-select
            v-model:value="formData.isVisibleToMemberCode"
            mode="multiple"
            allowClear
            max-tag-count="responsive"
            style="width: 100%"
            placeholder="请选择"
            :options="options.yesorno"
          >
          </a-select>
        </a-col>
      </a-row>
      <div class="gutter-search">
        <a-button type="primary" class="search-btn" @click="searchForm">{{
          $t('global.search')
        }}</a-button>
        <a-button @click="reset" class="reset-btn">{{ $t('global.reset') }}</a-button>
      </div>
    </div>
    <a-table
      class="ant-table-sub-striped"
      :columns="hospitalInfoColumns"
      :loading="loading"
      :scroll="{ x: '1300px', y: '350px' }"
      :data-source="dataSource"
      :pagination="pagination"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'index'">
          <div class="center">
            <span>{{ index + 1 }}</span>
          </div>
        </template>
        <template v-if="column.key === 'action'">
          <span class="table-operation" @click="handlePreAuth(record)">预授权</span>
        </template>
      </template>
    </a-table>
  </DraggableModal>
</template>
<style>
.pre-hospital-ellipsis-text {
  width: 280px;
  word-break: break-all;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; /* 这里是超出几行省略 */
  overflow: hidden;
}
</style>
<style lang="scss" scoped>
.ant-col-5 {
  flex: 0 0 20%;
  max-width: 20%;
}
.main-header {
  margin-bottom: 20px;
  .ant-input-affix-wrapper {
    box-sizing: border-box;
    padding-left: 15px;
    height: 32px;
    border-radius: 4px;
    border: 1px solid #dfdfdf;
  }
  .search-btn {
    margin-right: 16px;
  }
  .gutter-row {
    p {
      margin-bottom: 10px;
    }
    .search-icon {
      width: 100%;
      height: 100%;
      background: #729db0;
    }
  }
  .gutter-search {
    padding-top: 20px;
    display: flex;
    align-items: center;
    justify-content: end;
    .reset-btn {
      margin-right: 0px;
    }
  }
  .policy-year-box {
    width: 100%;
    height: 32px;
    display: flex;
    border-radius: 6px;
    background-color: #ffffff;
    border: 1px solid #d9d9d9;
    align-items: center;
    position: relative;
    justify-content: space-between;
    padding: 0 11px;
    .policy-year {
      font-size: 14px;
      color: #333333;
    }
    .arrow-year-icon {
      color: #ccc;
    }
  }
}
</style>
